package com.itheima.reggie.controller;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.converters.longconverter.LongStringConverter;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.LocalDateTimeConverter;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrdersService;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/order")
public class OrdersController {
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private ShoppingCartService shoppingCartService;

    @PostMapping("/submit")
    public R submit(@RequestBody Orders orders){
        ordersService.submit(orders);
        return R.success("支付成功,生成了订单");
    }




    @GetMapping("/userPage")
    public R page(int page, int pageSize){
        Page pageInfo=new Page<Orders>(page,pageSize);
        ordersService.page(pageInfo);
        List<Orders> records = pageInfo.getRecords();
        long total = pageInfo.getTotal();
        List<OrdersDto> collect = records.stream().map(orders -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(orders, ordersDto);
            LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(OrderDetail::getOrderId, ordersDto.getNumber());
            List<OrderDetail> detailList = orderDetailService.list(queryWrapper);
            ordersDto.setOrderDetails(detailList);
            return ordersDto;
        }).collect(Collectors.toList());
        Map map=new HashMap<>();
        map.put("records",collect);
        map.put("total",total);
        return R.success(map);
    }




    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String number, String beginTime, String endTime){
        Page<Orders> pageInfo = new Page(page,pageSize);
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(number != null,Orders::getId, number);
        queryWrapper.ge(beginTime != null,Orders::getOrderTime,beginTime);
        queryWrapper.le(endTime != null,Orders::getOrderTime,endTime);
        queryWrapper.orderByDesc(Orders::getCheckoutTime);
        ordersService.page(pageInfo,queryWrapper);
        List<Orders> records = pageInfo.getRecords();
        records.stream().map((item) -> {
            item.setUserName(String.valueOf(item.getUserId()));
            return item;
        }).collect(Collectors.toList());
        return R.success(pageInfo);
    }



    @PutMapping
    public R updateOrder(@RequestBody Orders orders){
        LambdaUpdateWrapper<Orders> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Orders::getId, orders.getId());
        updateWrapper.set(Orders::getStatus,orders.getStatus());
        ordersService.update(updateWrapper);
        return R.success("订单派送成功");
    }



    //再来一单
    @PostMapping("/again")
    public R again(@RequestBody Orders orders){
        Long id = orders.getId();
        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDetail::getOrderId,id);
        List<OrderDetail> orderDetailList = orderDetailService.list(queryWrapper);
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getId,id);
        shoppingCartService.remove(wrapper);
        Long userId = BaseContext.getCurrentId();
        List<ShoppingCart> list= orderDetailList.stream().map(shop -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(shop,shoppingCart);
            shoppingCart.setUserId(userId);
            Long dishId =shop.getDishId();
            Long setmealId = shop.getSetmealId();
            String dishFlavor = shop.getDishFlavor();
            if(dishId != null){
                shoppingCart.setDishId(dishId);
                shoppingCart.setDishFlavor(dishFlavor);
            }else {
                shoppingCart.setSetmealId(setmealId);
            }
            shoppingCart.setName(shop.getName());
            shoppingCart.setNumber(shop.getNumber());
            shoppingCart.setAmount(shop.getAmount());
            shoppingCart.setImage(shop.getImage());
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());
        shoppingCartService.saveBatch(list);
        return R.success("再来一单成功");
    }



    @GetMapping("/export")
    public R export(HttpServletResponse response) throws IOException {
        String fileName= URLEncoder.encode("订单明细","UTF-8");
        response.setHeader("Content-Disposition","attachment;filename="+fileName+".xlsx");
        ServletOutputStream outputStream = response.getOutputStream();
        ExcelWriterBuilder write = EasyExcel.write(outputStream,Orders.class).registerConverter
                (new LocalDateTimeConverter()).registerConverter(new LongStringConverter());
        ExcelWriterSheetBuilder sheet=write.sheet();
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        List<Orders> list = ordersService.list(queryWrapper);
        sheet.doWrite(list);
        outputStream.close();
        return R.success("导出Excel成功");
    }
}